package dao

import (
	"github.com/astaxie/beego/orm"
	"github.com/pkg/errors"
	"nft-server/common"
	"nft-server/model"
)

type BurnAssetDao struct {
	BaseDao
}

type IBurnAssetDao interface {
	InsertBurnAsset(asset *model.BurnAsset) error
	GetOneBurnAsset(operatingStatus int) (*model.BurnAsset, error)
	GetBurnAssetByCollectionId(queryBurnAssetParameter *common.QueryBurnAssetInfo) ([]*model.BurnAsset, error)
	UpdateBurnAssetOperatingStatus(BurnAssetId, operatingStatus int) error
	DelOneBurnAsset(BurnAssetId int) error
}

func GetBurnAssetDao() IBurnAssetDao {
	dao := &BurnAssetDao{}
	dao.Init()
	return dao
}

func (bad *BurnAssetDao) InsertBurnAsset(burnAssetInfo *model.BurnAsset) error {
	_, err := bad.O.Insert(burnAssetInfo)
	if err != nil {
		return errors.Errorf("InsertBurnAsset error: %v", err)
	}
	return nil
}

func (bad *BurnAssetDao) GetOneBurnAsset(operatingStatus int) (*model.BurnAsset, error) {
	BurnAsset := new(model.BurnAsset)
	err := bad.O.QueryTable(new(model.BurnAsset)).Filter("operating_status", operatingStatus).One(BurnAsset)
	if err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, errors.Errorf("read error: %v", err)
	}
	return BurnAsset, nil
}

func (bad *BurnAssetDao) UpdateBurnAssetOperatingStatus(BurnAssetId, operatingStatus int) error {
	burnAssetDetail := new(model.BurnAsset)
	burnAssetDetail.Id = BurnAssetId
	burnAssetDetail.OperatingStatus = operatingStatus
	_, err := bad.O.Update(burnAssetDetail, "operating_status")
	if err != nil {
		return errors.Errorf("update error: %v", err)
	}
	return nil
}

func (bad *BurnAssetDao) DelOneBurnAsset(burnAssetId int) error {
	BurnAsset := new(model.BurnAsset)
	BurnAsset.Id = burnAssetId
	_, err := bad.O.Delete(BurnAsset, "id")
	if err != nil {
		return errors.Errorf("delete error: %v", err)
	}
	return nil
}

func (bad *BurnAssetDao) GetBurnAssetByCollectionId(queryBurnAssetParameter *common.QueryBurnAssetInfo) (burnAssets []*model.BurnAsset, err error) {
	recode := bad.O.QueryTable(&model.BurnAsset{})
	finalCondition := orm.NewCondition()
	finalCondition = finalCondition.And("collection_index", queryBurnAssetParameter.CollectionIndex)
	if queryBurnAssetParameter.SubCollectionIndex != nil {
		finalCondition = finalCondition.And("sub_collection_index", *queryBurnAssetParameter.SubCollectionIndex)
	}
	recode = recode.SetCond(finalCondition).RelatedSel()
	_, err = recode.All(&burnAssets)
	if err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, errors.Errorf("read error: %v", err)
	}
	return burnAssets, nil
}
